package cn.bytepulse.web.auth.service.impl;

import cn.bytepulse.constant.HttpStatus;
import cn.bytepulse.exception.QuicklyException;
import cn.bytepulse.web.admin.entity.SysUser;
import cn.bytepulse.web.admin.mapper.SysUserMapper;
import cn.bytepulse.web.admin.service.UserService;
import cn.bytepulse.web.auth.dao.LoginUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * 用户信息加载
 *
 * @author jiejiebiezheyang
 * @since 2024-03-02 22:00
 */
@Service
@RequiredArgsConstructor
public class UserDetailServiceImpl implements UserDetailsService {

    private final SysUserMapper sysUserMapper;

    private final UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws RuntimeException {
        // 从数据库获取用户信息
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        SysUser sysUser = sysUserMapper.selectOne(wrapper);
        if (sysUser == null) {
            throw new QuicklyException(HttpStatus.LOGIN_ERROR);
        } else if ("00".equals(sysUser.getStatus())) {
            throw new QuicklyException(HttpStatus.LOGIN_NO);
        } else {
            // 用户权限信息
            Set<String> authorities = userService.permissions(sysUser.getId());
            return new LoginUser(sysUser, authorities);
        }
    }
}
